/* 
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.core.tabs;

import java.awt.LayoutManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.settings.ConvertAsProperties;
import org.netbeans.modules.tfsnb.core.ConnectionService;
import org.netbeans.modules.tfsnb.core.ConnectionSettings;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//org.netbeans.modules.tfsnb.core//TFSConnectionExplorer//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "TFSConnectionExplorerTopComponent",
        iconBase = "org/netbeans/modules/tfsnb/core/TeamFoundationServer.gif",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "editor", openAtStartup = false, position = 1000)
@ActionID(category = "Window", id = "org.netbeans.modules.tfsnb.core.TFSConnectionExplorerTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_TFSConnectionExplorerAction",
        preferredID = "TFSConnectionExplorerTopComponent"
)
@Messages({
    "CTL_TFSConnectionExplorerAction=TFSConnectionExplorer",
    "CTL_TFSConnectionExplorerTopComponent=TFSConnectionExplorer Window",
    "HINT_TFSConnectionExplorerTopComponent=This is a TFSConnectionExplorer window"
})
public final class TFSConnectionExplorerTopComponent extends TopComponent implements ChangeListener {
    
    public TFSConnectionExplorerTopComponent() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
     * content of this method is always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        headerPanel = new javax.swing.JPanel();
        bodyTabbedPane = new javax.swing.JTabbedPane();

        setLayout(new java.awt.BorderLayout());

        headerPanel.setMaximumSize(new java.awt.Dimension(25, 28));
        headerPanel.setMinimumSize(new java.awt.Dimension(25, 28));
        headerPanel.setPreferredSize(new java.awt.Dimension(25, 28));

        javax.swing.GroupLayout headerPanelLayout = new javax.swing.GroupLayout(headerPanel);
        headerPanel.setLayout(headerPanelLayout);
        headerPanelLayout.setHorizontalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 588, Short.MAX_VALUE)
        );
        headerPanelLayout.setVerticalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 28, Short.MAX_VALUE)
        );

        add(headerPanel, java.awt.BorderLayout.PAGE_START);
        add(bodyTabbedPane, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    public void addComponents() {
        
        addViews();
        setName(Bundle.CTL_TFSConnectionExplorerTopComponent());
        setToolTipText(Bundle.HINT_TFSConnectionExplorerTopComponent());
        
        String title = bodyTabbedPane.getTitleAt(bodyTabbedPane.getSelectedIndex());
        headerPanel.removeAll();
        JToolBar toolbar = (JToolBar) tabTitleToolBarMap.get(title);
        headerPanel.add(toolbar);
        javax.swing.GroupLayout headerPanelLayout = new javax.swing.GroupLayout(headerPanel);
        headerPanel.setLayout(headerPanelLayout);
        headerPanelLayout.setHorizontalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(toolbar, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
        );
        headerPanelLayout.setVerticalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(toolbar, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
        );
    }
    
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
    
    private void addMultiViewManager(ConnectionSettings connectionSettings) {
        try {
            multiViewManager = new TabManager(this, connectionSettings);
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, ex.getMessage());
        }
    }
    
    private void addViews() {
        Map<String, TabPanel> views = multiViewManager.getViews(false);
        for(TabPanel view: views.values()) {
            JComponent visualRepresentation = view.getVisualRepresentation();
            TabPanelDescription description = view.getMultiViewPanelDescription();
            bodyTabbedPane.addTab(description.getDisplayName(), ImageUtilities.loadImageIcon(description.getIconBase(), true), visualRepresentation);
            tabTitleToolBarMap.put(description.getDisplayName(), view.getToolbarRepresentation());
        }
    }    
    
    @Override
    public void stateChanged(ChangeEvent e) {
        JTabbedPane tabs = (JTabbedPane) e.getSource();
        String title = tabs.getTitleAt(tabs.getSelectedIndex());
        headerPanel.removeAll();
        headerPanel.add(tabTitleToolBarMap.get(title));
    }    

    public ConnectionSettings getConnectionSettings() {
        return connectionSettings;
    }

    public void setConnectionSettings(ConnectionSettings connectionSettings) {
        this.connectionSettings = connectionSettings;
        if(multiViewManager == null ) addMultiViewManager(connectionSettings);        
        Map<String, TabPanel> views = multiViewManager.getViews(false);
        for(TabPanel view: views.values()) {
            view.setConnectionSettings(connectionSettings);
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTabbedPane bodyTabbedPane;
    private javax.swing.JPanel headerPanel;
    // End of variables declaration//GEN-END:variables
    private final ArrayList<Class> panelClasses = new ArrayList<>();    
    private LayoutManager jPanel1Layout;
    private TabManager multiViewManager;
    private static final Logger LOG = Logger.getLogger(TFSConnectionExplorerTopComponent.class.getName());
    private static final Map<String, JComponent> tabTitleToolBarMap = new HashMap<>();
    private ConnectionSettings connectionSettings;
    
}
